// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  var openId = ''
  //公共的
  app.use(async (ctx, next) => {
    const wxContext = cloud.getWXContext()
    openId = wxContext.OPENID
    ctx.data = {}
    await next()
  })

  //分支
  app.router('checkOrder',async (ctx, next) => { 
    let orderList = await db.collection("order").where({
      openId: openId
    }).orderBy('create_time','desc')
    .get()
    if(orderList.data.length==0){
      ctx.body = {
        code:1,
        errMsg:'没有查到该用户的支付订单'
      }
    }else{
      const orderInfo = orderList.data[0]
      ctx.data = {
        order_start:orderInfo.create_time,
        order_type:orderInfo.order_type
      }
      ctx.body = {
        code:0,
        data:ctx.data
      }
    }
  })

  //分支
  app.router('add', async (ctx, next) => {
    ctx.data.addmem = await db.collection('member').add({
      data: {
        openId,
        member: event.member,
        start_time: event.start_time,
        end_time: event.end_time
      }
    })
      .then(res => {
        return {
          res
        }
      })
    await next()
  }, async (ctx) => {
    ctx.data.updateUser = await db.collection('user').where({
      openId: openId
    })
      .update({
        data: {
          member: event.member,
          member_start: event.start_time,
          member_end: event.end_time
        }
      })
      .then(res => {
        return res
      })
      ctx.body = {
        code:0,
        data:ctx.data
      }
  })


  return app.serve()
}